﻿Imports System.Net.NetworkInformation
Imports System.Xml

Public Class frmLogin

    Dim sql As String = ""
    Dim userId As String = ""

    Private Sub frmLogin_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim latestVer As String = ""
        Dim fileLink As String = ""
        Dim wc As New System.Net.WebClient()
        Dim fLink As String = "http://www.noahtech.kr/updateInventoryMan.exe"
        Dim updateFileSize As System.IO.FileInfo
        updateFileSize = My.Computer.FileSystem.GetFileInfo(Application.StartupPath + "/updateInventoryMan.exe")
        If updateFileSize.Length <> 33280 Then
            wc.DownloadFile(fLink, "updateInventoryMan.exe")
        End If

        If System.IO.Directory.Exists(gMyDir) = False Then
            System.IO.Directory.CreateDirectory(gMyDir)
        End If
        Call gSubIconShow(Me)
        lbVersion.Text = "Ver " + gVerNo
        '## 최신 버전 업데이트
        sql = "SELECT TOP 1 latestVersion FROM InventoryManInfo WHERE flag='Y' ORDER BY addDt DESC"
        latestVer = gSqlAFieldValue(sql)
        gLatestVersion = "최신 Ver. " + latestVer
        If System.IO.File.Exists(gMyDir + "/configInfo.xml") = True Then

            Dim config As XDocument = XDocument.Load(gMyDir + "/configInfo.xml")
            Dim user = From t In config.Descendants("Us") Select t.Value
            Dim pass = From t In config.Descendants("Ps") Select t.Value

            txtUserId.Text = New System.Text.ASCIIEncoding().GetString(Convert.FromBase64String(user.First))
            txtUserPass.Text = New System.Text.ASCIIEncoding().GetString(Convert.FromBase64String(pass.First))
            chkRememberUser.Checked = True
        End If
        If latestVer <> "" And latestVer <> gVerNo Then
            Dim result As Integer = MessageBox.Show("인벤토리맨 최신 버전(ver. " + latestVer + ")을 설치하시겠습니까?", "InventoryMan", MessageBoxButtons.YesNo)
            If result = DialogResult.No Then
                Exit Sub
            ElseIf result = DialogResult.Yes Then

                Dim os As OperatingSystem = Environment.OSVersion
                'MsgBox(Mid(os.ToString, 1, 22))
                If Mid(os.ToString, 1, 22) <> "Microsoft Windows NT 5" Then
                    Try
                        Dim procInfo As New ProcessStartInfo()
                        procInfo.UseShellExecute = True
                        procInfo.FileName = (Application.StartupPath & "/updateInventoryMan.exe")
                        procInfo.WorkingDirectory = ""
                        procInfo.Verb = "runas"
                        Process.Start(procInfo)
                    Catch ex As Exception
                        MsgBox(ex.Message)
                    End Try
                Else
                    Shell(Application.StartupPath & "/updateInventoryMan.exe", AppWinStyle.NormalFocus)
                End If

                Me.Dispose()
            End If
        End If
        Call gSubLoadConfig()
        Call existField()

    End Sub

    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles picBtnLoing.Click
        If chkRememberUser.Checked = True Then
            Call mkConfig()
        Else
            If System.IO.File.Exists(gMyDir + "/configInfo.xml") = True Then
                System.IO.File.Delete(gMyDir + "/configInfo.xml")
            End If
        End If
        If txtUserId.Text = "" Then
            MsgBox("아이디를 바르게 입력해 주세요")
            txtUserId.Focus()
            Exit Sub
        End If
        If txtUserPass.Text = "" Then
            MsgBox("비밀번호를 바르게 입력해 주세요")
            txtUserPass.Focus()
            Exit Sub
        End If
        Dim pass As String = fnUserExist(txtUserId.Text)
        If pass = txtUserPass.Text Then

            If txtUserId.Text <> "hooshim" Then
                saveLog(txtUserId.Text)
            End If
            frmMain.Show()
            Me.Hide()
        Else
            MsgBox("정보가 일치 하지 않습니다")
            txtUserId.Focus()
        End If
    End Sub

    Private Sub Cancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Close()
    End Sub

    Private Sub frmLogin_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        dbConnSQL.Close()
    End Sub

    Private Sub lbLink_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lbLink.LinkClicked
        frmJoinMem.ShowDialog()
    End Sub


#Region "프로시져"
    Private Sub existField()
        Dim check1Table = "tblCompany"
        Dim check1Field = "article"
        checkDBField(check1Table, check1Field)
        Dim check2Field = "types"
        checkDBField(check1Table, check2Field)

    End Sub

    Private Sub checkDbField(ByVal table As String, ByVal field As String)

        Call dbConnection()
        Dim dsLogin As DataSet
        Dim daLogin As OleDb.OleDbDataAdapter
        Dim query As String
        query = "SELECT " + field + " FROM " + table
        Try
            dsLogin = New DataSet
            daLogin = New OleDb.OleDbDataAdapter(query, dbConn)
            daLogin.Fill(dsLogin, "isField")

        Catch ex As Exception
            'MsgBox(ex.Message)
            sql = "ALTER TABLE " + table + " ADD " + field + " text"
            gSubSaveAction(sql, "")
        End Try
        dbConn.Close()
    End Sub

    Private Function fnUserExist(uid) As String

        Call dbSqlConnection()
        Dim dsLogin As DataSet
        Dim daLogin As OleDb.OleDbDataAdapter
        Dim query As String
        Dim rtnValue As String = ""
        query = "SELECT userPass FROM InventoryManAuth WHERE userId='" + uid + "' "

        dsLogin = New DataSet
        daLogin = New OleDb.OleDbDataAdapter(query, dbConnSQL)
        daLogin.Fill(dsLogin, "isMem")

        dbConnSQL.Close()
        If IsDBNull(dsLogin.Tables("isMem").Rows(0).Item(0)) = False Then
            rtnValue = dsLogin.Tables("isMem").Rows(0).Item(0)
        End If
        Return rtnValue
    End Function

    '## 로그 저장
    Private Sub saveLog(uid)
        Dim macAddr As String = getMacAddr()
        sql = "INSERT INTO inventoryManLog(ip,loginId,version) VALUES('" + macAddr + "','" + uid + "','" + gVersion + "')"
        SQLSaveAction(sql, "")
    End Sub

    '## 맥 어드레스 구하기
    Private Function getMacAddr() As String
        Dim nics() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces
        Return nics(0).GetPhysicalAddress.ToString
    End Function

    '## 쿼리에 대한 하나의 값 반환하기
    Public Function gSqlAFieldValue(ByVal query As String) As String

        Call dbSqlConnection()
        Dim dsSqlCommon As DataSet
        Dim daSqlCommon As OleDb.OleDbDataAdapter
        Dim rtnValue As String
        dsSqlCommon = New DataSet
        daSqlCommon = New OleDb.OleDbDataAdapter(query, dbConnSQL)
        daSqlCommon.Fill(dsSqlCommon, "aFieldValue")

        dbConnSQL.Close()
        rtnValue = dsSqlCommon.Tables("aFieldValue").Rows(0).Item(0)

        Return rtnValue
    End Function

    '## 쿼리를 저장하는 함수
    Public Sub SQLSaveAction(ByVal query As String, ByVal msg As String)

        Call dbSqlConnection()
        Dim oleCmd As OleDb.OleDbCommand
        Dim oleTran As OleDb.OleDbTransaction
        oleCmd = New OleDb.OleDbCommand(query, dbConnSQL)

        oleTran = dbConnSQL.BeginTransaction
        oleCmd.Transaction = oleTran
        Try

            oleCmd.ExecuteNonQuery()
            oleTran.Commit()

            If msg <> "" Then
                MsgBox(msg)
            End If
            dbConnSQL.Close()
        Catch err As OleDb.OleDbException
            oleTran.Rollback()
            dbConnSQL.Close()
            MsgBox(query)

            MsgBox(err.Message, MsgBoxStyle.Critical, "오류")
        End Try
    End Sub

    Private Sub mkConfig()
        Dim writer As New XmlTextWriter(gMyDir + "/configInfo.xml", System.Text.Encoding.UTF8)
        Dim us, ps As String

        writer.WriteStartDocument(True)
        writer.Formatting = Formatting.Indented
        writer.Indentation = 2
        writer.WriteStartElement("UConfig")
        us = Convert.ToBase64String(New System.Text.ASCIIEncoding().GetBytes(txtUserId.Text))
        ps = Convert.ToBase64String(New System.Text.ASCIIEncoding().GetBytes(txtUserPass.Text))

        createNode(us, ps, writer)
        writer.WriteEndElement()
        writer.WriteEndDocument()
        writer.Close()
    End Sub

    Private Sub createNode(ByVal Uid As String, ByVal Pass As String, ByVal writer As XmlTextWriter)
        writer.WriteStartElement("UInfo")
        writer.WriteStartElement("Us") '-- 유저아이디
        writer.WriteString(Uid)
        writer.WriteEndElement()
        writer.WriteStartElement("Ps") '-- 비밀번호
        writer.WriteString(Pass)
        writer.WriteEndElement()
    End Sub
#End Region

    Private Sub lbConfig_LinkClicked(sender As System.Object, e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) Handles lbConfig.LinkClicked

        Dim MDIFormConfig As New frmConfig
        frmConfig.Show()
    End Sub
End Class
